package com.atguigu.gmall.all.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.product.client.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import javax.servlet.http.HttpServletRequest;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @version 1.0
 * @Author 杨旭康
 * @Date 2023/1/31 17:16
 * @question:
 */

@Controller
@SuppressWarnings("all")
public class IndexController {

    @Autowired
    private ProductFeignClient productFeignClient;

    /**
     * index页面的显示方式1 -> 页面渲染
     * www.gmall.com/index.html
     * @param request
     * @return
     */
    @GetMapping({"/","index.html"})
    public String index(Model model){
        // 获取首页分类数据
        Result result = productFeignClient.getBaseCategoryList();
        model.addAttribute("list",result.getData());

        return "index/index";
    }

    /**
     * 模板引擎
     */
    @Autowired
    private TemplateEngine templateEngine;

    /**
     * index页面的显示方式2 -> 使用nginx反向代理操作
     * nginx端口号不要使用 80
     * @param request
     * @return
     */
    @GetMapping("createIndex")
    @ResponseBody
    public Result createIndex(){
        // 获取首页分类数据
        Result result = productFeignClient.getBaseCategoryList();

        //创建一个响应上下文对象
        Context context = new Context();
        context.setVariable("list",result.getData());

        //  定义文件输入位置
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter("D:\\index.html");
        } catch (IOException e) {
            e.printStackTrace();
        }

        //开始解析 创建模板
        templateEngine.process("/index/index.html",context,fileWriter);

        return Result.ok();
    }


}
